package com.androidvizlab.bachelor.utilities;

import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

/**
 * This class is used to acquire and release of a wakelock through 
 * android's PowerManager and Power service
 * @author The Hive
 */
public class WakeLockManager {

	private static PowerManager pwr_manager = null;
	private static WakeLock wakelock = null;
	
	/**
	 * Acquire a wakelock to keep the cpu from sleeping
	 * @param context
	 */
	public static void acquire(Context context,String tag)
	{
		if(wakelock != null)
		{
			release();
		}
		
		pwr_manager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		/*wakelock = pwr_manager.newWakeLock(PowerManager.FULL_WAKE_LOCK |
				PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "wakeup");*/
		wakelock = pwr_manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, tag);
		
		wakelock.acquire();
	}
	
	/**
	 * This releases the acquired wakelock
	 */
	public static void release()
	{
		if(wakelock != null)
		{
			wakelock.release();
		}
	}
	
	/**
	 * Turns the screen off(Not in used)
	 * @param context
	 * @param tag
	 */
	public static void screenOff(Context context, String tag)
	{
		if(wakelock != null)
		{
			release();
		}
		
		pwr_manager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		
		wakelock = pwr_manager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, tag);
		
		wakelock.acquire();
		
		if(wakelock != null && wakelock.isHeld())
		{
			wakelock.release();
		}
	}
}
